package com.vhall.component.service.goods.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vhall.component.dao.goods.GoodsMapper;
import com.vhall.component.dao.goods.LiveGoodsMapper;
import com.vhall.component.dao.goods.LiveGoodsStatsMapper;
import com.vhall.component.dao.room.RoomGoodsMapper;
import com.vhall.component.entity.goods.GoodsEntity;
import com.vhall.component.entity.goods.LiveGoodsEntity;
import com.vhall.component.entity.goods.goods.GoodsApiSendMessageReqVO;
import com.vhall.component.entity.goods.goods.GoodsApiSetGoodsSwitchReqVO;
import com.vhall.component.entity.goods.goods.GoodsPushScreenReqVO;
import com.vhall.component.entity.goods.vo.GetGoodsInfoRequestVO;
import com.vhall.component.entity.goods.vo.GetGoodsInfoResponseVO;
import com.vhall.component.entity.room.dto.RoomsEntityDTO;
import com.vhall.component.entity.room.entity.RoomGoodsEntity;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.constant.PaasCommonConstant;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.properties.ThirdPartyProperties;
import com.vhall.component.plugin.common.utils.JsonUtil;
import com.vhall.component.plugin.core.enums.SendMessageTypeEnum;
import com.vhall.component.plugin.core.service.PaasService;
import com.vhall.component.plugin.core.service.event.PaasMessageReqDTO;
import com.vhall.component.service.goods.GoodsApiService;
import com.vhall.component.service.goods.GuoxinPrdService;
import com.vhall.component.service.goods.LiveGoodsConsoleService;
import com.vhall.component.service.goods.LiveGoodsStatsService;
import com.vhall.component.service.goods.common.GoodsConstant;
import com.vhall.component.service.room.RoomInnerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author guoxin.wang
 * @date 2021-06-26 10:15
 */

@Slf4j
@Service
public class GoodsApiServiceImpl implements GoodsApiService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private LiveGoodsMapper liveGoodsMapper;

    @Autowired
    private LiveGoodsStatsMapper liveGoodsStatsMapper;

    @Autowired
    private RoomInnerService roomInnerService;

    @Autowired
    private PaasService paasService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LiveGoodsStatsService liveGoodsStatsService;

    @Autowired
    private LiveGoodsConsoleService liveGoodsConsoleService;
    @Resource
    private GuoxinPrdService guoxinPrdService;
    @Resource
    private ThirdPartyProperties thirdPartyProperties;
    @Resource
    private RoomGoodsMapper roomGoodsMapper;

    @Override
    public Boolean pushScreen(GoodsApiSendMessageReqVO reqVO) {
        return pushScreenMain(reqVO);
//        return pushScreeTest(reqVO);
    }

    private boolean pushScreeTest(GoodsApiSendMessageReqVO reqVO) {
        Integer bcgId = reqVO.getBcgId();

        GetGoodsInfoRequestVO guoxinProInfoVO = new GetGoodsInfoRequestVO();

        String[] split = thirdPartyProperties.getProd().getCodes().split("\\|");
        int length = split.length;
        int index = bcgId % length;
        guoxinProInfoVO.setPrdCodes(split[index]);
        List<GetGoodsInfoResponseVO> goodsInfoList = guoxinPrdService.getGoodsInfoList(guoxinProInfoVO);
        GetGoodsInfoResponseVO getGoodsInfoResponseVO = goodsInfoList.get(0);

        // 2、获取房间信息
        RoomsEntityDTO roomInfo = roomInnerService.getRoomInfo(reqVO.getRoomId());
        if (roomInfo == null) {
            throw new BusinessException(BizErrorCode.EMPTY_ROOM);
        }
        // 5、发送消息
        JSONObject messageBody = (JSONObject) JSONObject.toJSON(getGoodsInfoResponseVO);
        /*
         * 消息类型：
         *  3001-推屏，2000-点赞，1010-禁言，1011-取消禁言，3000-暂停，
         *  3010-播放中，3011-停止播放，1000-增加为用户数，1012-新增边拍边买商品
         */
        messageBody.put("type", GoodsConstant.RECORD_TYPE_3001);
        messageBody.put("bcg_id", bcgId);
        String prdCode = getGoodsInfoResponseVO.getPrdCode();
//            系统内商品 id
        int bgId = Objects.nonNull(prdCode)?prdCode.hashCode():bcgId;
        if (bgId<=0) {
            bgId = bcgId;
        }
        messageBody.put("bg_id", bgId);
        log.info("messageBody:{}",messageBody.toString());
        PaasMessageReqDTO paasMessageReq = new PaasMessageReqDTO.Builder(roomInfo.getChannelId(), messageBody.toString())
                .initDefault().build();
        paasMessageReq.setType("service_custom");
        paasService.sendMessage(paasMessageReq);
        return true;
    }

    private Boolean pushScreenMain(GoodsApiSendMessageReqVO reqVO) {
        // 1、获取商品绑定信息
        RoomGoodsEntity roomGoodsEntity = roomGoodsMapper.selectById(reqVO.getBcgId());
        GetGoodsInfoRequestVO requestVO = new GetGoodsInfoRequestVO();
        requestVO.setPrdCodes(roomGoodsEntity.getPrdType() + "." + roomGoodsEntity.getPrdCode());
        requestVO.setIlId(roomGoodsEntity.getIlId());
        List<GetGoodsInfoResponseVO> goodsInfoList = guoxinPrdService.getGoodsInfoList(requestVO);
        if (CollUtil.isEmpty(goodsInfoList)){
            throw new BusinessException(60000,"未查询到商品信息","");
        }
        // 1.5、获取商品信息
        GetGoodsInfoResponseVO getGoodsInfoResponseVO = goodsInfoList.get(0);

        // 2、获取房间信息
        RoomsEntityDTO roomInfo = roomInnerService.getRoomInfo(reqVO.getRoomId());
        if (roomInfo == null) {
            throw new BusinessException(BizErrorCode.EMPTY_ROOM);
        }

        LocalDateTime now = LocalDateTime.now();
        // 5、发送消息
        JSONObject messageBody = new JSONObject();
        /*
         * 消息类型：
         *  3001-推屏，2000-点赞，1010-禁言，1011-取消禁言，3000-暂停，
         *  3010-播放中，3011-停止播放，1000-增加为用户数，1012-新增边拍边买商品
         */
        messageBody.put("type", GoodsConstant.RECORD_TYPE_3001);
        messageBody.put("bcg_id", reqVO.getBcgId());
        messageBody.put("bg_id", reqVO.getBcgId());
        messageBody.put("name", getGoodsInfoResponseVO.getPrdName());
        messageBody.put("goods_url", getGoodsInfoResponseVO.getWxUrl());
        messageBody.put("goods_url_android", getGoodsInfoResponseVO.getJtyUrl());
        messageBody.put("goods_url_ios", getGoodsInfoResponseVO.getJtyUrl());
        messageBody.put("pic", "");
        messageBody.put("screen_second", reqVO.getScreenSecond());
        messageBody.put("goods_tag", "");
        messageBody.put("product_button_text", "");
        messageBody.put("sort", 0);
        PaasMessageReqDTO paasMessageReq = new PaasMessageReqDTO.Builder(roomInfo.getChannelId(), messageBody.toString())
                .initDefault().build();
        paasMessageReq.setType("service_custom");
        paasService.sendMessage(paasMessageReq);

        // 3、推屏成功，更新统计信息
        return liveGoodsStatsService.handleUpdateGoodsStats(reqVO, roomGoodsEntity, now);
    }

    @NotNull
    private LiveGoodsEntity getPushLiveGoodsEntity(GoodsApiSendMessageReqVO reqVO) {
        LambdaQueryWrapper<LiveGoodsEntity> queryLiveGoods = Wrappers.lambdaQuery();
        queryLiveGoods.eq(LiveGoodsEntity::getBcgId, reqVO.getBcgId())
                .eq(LiveGoodsEntity::getGoodsStatus, GoodsConstant.GOODS_STATUS_ON);
        LiveGoodsEntity bindInfo = liveGoodsMapper.selectOne(queryLiveGoods);
        if (bindInfo == null) {
            throw new BusinessException(BizErrorCode.EMPTY_GOODS);
        }
        return bindInfo;
    }

    @Override
    public Boolean setGoodsSwitch(GoodsApiSetGoodsSwitchReqVO reqVO) {
        RoomsEntityDTO roomInfo = roomInnerService.getRoomInfo(reqVO.getRoomId());
        if (roomInfo == null) {
            throw new BusinessException(BizErrorCode.EMPTY_ROOM);
        }
        // 1、在缓存中存储该按钮信息。
        redisTemplate.opsForHash().put(RedisKey.INTERACT_TOOL + reqVO.getRoomId(), GoodsConstant.LIVE_GOODS_ENTRANCE_SWITCH_KEY,
                reqVO.getStatus());
        // 2、发送消息通知商品列表。
        JSONObject messageBody = new JSONObject();
        messageBody.put("type", GoodsConstant.RECORD_TYPE_4001);
        messageBody.put(PaasCommonConstant.STATUS, reqVO.getStatus());
        //清除缓存
        liveGoodsConsoleService.delFirstPageGoodsCache(roomInfo.getIlId());
        PaasMessageReqDTO paasMessageReq = new PaasMessageReqDTO.Builder(roomInfo.getChannelId(), messageBody.toString())
                .initDefault().build();
        paasMessageReq.setType("service_custom");
        paasService.sendMessage(paasMessageReq);
        return true;
    }

    @Override
    public Boolean cancelPushScreen(GoodsPushScreenReqVO reqVO) {
        RoomGoodsEntity roomGoodsEntity = roomGoodsMapper.selectById(reqVO.getId());
        if (roomGoodsEntity == null){
            throw new BusinessException(60000,"未查询到商品信息","");
        }
//		判断房间是否存在
        RoomsEntityDTO roomInfo = roomInnerService.getRoomInfoById(reqVO.getIlId());
        if (roomInfo == null) {
            throw new BusinessException(BizErrorCode.EMPTY_ROOM);
        }

//		推送消息取消商品推屏
        JSONObject object = new JSONObject();
        object.put("type", SendMessageTypeEnum.CLOSE_PUSH_SCREEN_GOODS.getType());
        object.put("id", roomGoodsEntity.getId());
        object.put("prd_code", roomGoodsEntity.getPrdCode());
        String body = JsonUtil.toJsonString(object);
        String channelId = roomInfo.getChannelId();
        paasService.sendMessage(channelId, body);
        return true;
    }
}
